/* -*- mode: c++ -*-
** control.cpp
** 
** Made by Kjetil Svarstad
** 
*/

#include "control.h"

int Control::X[9] = {3,8,1,2,9,5,7,6,4};

// Functionality for the Control class

// Constructor
Control::Control (sc_module_name name) : sc_module (name)
{ // Constructor code
	SC_HAS_PROCESS (Control);
  SC_THREAD(main);
  arrayPos = 0;
}

void Control::buttonPushed(int buttonNumber)
{
	if(buttonNumber == 0)
	{ // Start button was pushed. Lights off and randomize buttonsequence.
		busp->switchLight(false);
		arrayPos = 0;
		// Shuffle the X array to generate a new sequence.
		int temp, rand1;
		for(int i = 0;i++; i <= 8)
		{
			rand1 = rand() % 9; // Random position in X
			// Switch elements in X[i] with element in random pos.
			// Elements are allowed to switch with themselves.
			temp = X[i];
			X[i] = X[rand1];
			X[rand1] = temp;
		}
	}
	else
	{
		if(arrayPos <= 8)
		{// Prevent out of bounds.
		 // All lights are on and only the startbutton should be acknowledged at
		 // this point.
			if(buttonNumber == X[arrayPos++])
			{ // Correct button pushed. Increment array pos and turn on light.
				busp->switchLight(true);
			}
			else
			{// Wrong button was pushed; turn off all lights, keep sequence.
				busp->switchLight(false);
				arrayPos = 0;
			}
		}
	}
	buttonPushedEvent.notify();
}

void Control::main()
{
	while(true)
	{
		wait(buttonPushedEvent);
	}
}
	
